from tkinter import *
from wincener import center
import random
import time
import threading
from selenium import webdriver
import time
import json
from pprint import pprint
import requests
s = requests.session()
s.keep_alive = False
post = {}



isdo = 0
zan_count = 0
zhuanfa_count = 0
liuyan_count = 0
zan_max = 10
zhuanfa_max = 500
liuyan_max = 500
isscroll = 0
willdo = 0
nownum = 0

cn_liuyan = "精彩拍摄"
en_liuyan = "Wonderful shooting"
login_no = '13816146456'
login_pw = "hjy11911xx"

def fun():
    print('初始化')
    driver = webdriver.Chrome(executable_path='chromedriver.exe')
    driver.get('https://mp.weixin.qq.com/')
    time.sleep(2)
    driver.find_element_by_xpath("./*//input[@name='account']").clear()
    driver.find_element_by_xpath("./*//input[@name='account']").send_keys('guocdfeifei@163.com')
    driver.find_element_by_xpath("./*//input[@name='password']").clear()
    driver.find_element_by_xpath("./*//input[@name='password']").send_keys('666666pin')
    # 在自动输完密码之后记得点一下记住我
    time.sleep(5)
    driver.find_element_by_xpath("./*//a[@class='btn_login']").click()
    # 拿手机扫二维码！
    time.sleep(15)
    driver.get('https://mp.weixin.qq.com/')
    cookie_items = driver.get_cookies()
    for cookie_item in cookie_items:
        post[cookie_item['name']] = cookie_item['value']
    cookie_str = json.dumps(post)
    with open('cookie.txt', 'w+', encoding='utf-8') as f:
        f.write(cookie_str)

def fun1():
    print('获取文章列表')

    url = 'https://mp.weixin.qq.com'
    # session.get(url)

    # s.get(url) # 你需要的网址
    gzlist = ['新浪新闻']

    header = {
        "HOST": "mp.weixin.qq.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0"
    }

    with open('cookie.txt', 'r', encoding='utf-8') as f:
        cookie = f.read()
    cookies = json.loads(cookie)
    response = requests.get(url=url, cookies=cookies)
    token = re.findall(r'token=(\d+)', str(response.url))[0]
    for query in gzlist:
        query_id = {
            'action': 'search_biz',
            'token': token,
            'lang': 'zh_CN',
            'f': 'json',
            'ajax': '1',
            'random': random.random(),
            'query': query,
            'begin': '0',
            'count': '5',
        }
        search_url = 'https://mp.weixin.qq.com/cgi-bin/searchbiz?'
        search_response = requests.get(search_url, cookies=cookies, headers=header, params=query_id)
        lists = search_response.json().get('list')[0]
        fakeid = lists.get('fakeid')
        query_id_data = {
            'token': token,
            'lang': 'zh_CN',
            'f': 'json',
            'ajax': '1',
            'random': random.random(),
            'action': 'list_ex',
            'begin': '0',
            'count': '5',
            'query': '',
            'fakeid': fakeid,
            'type': '9'
        }
        appmsg_url = 'https://mp.weixin.qq.com/cgi-bin/appmsg?'
        appmsg_response = requests.get(appmsg_url, cookies=cookies, headers=header, params=query_id_data)
        max_num = appmsg_response.json().get('app_msg_cnt')
        num = int(int(max_num) / 5)
        begin = 0
        while num + 1 > 0:
            query_id_data = {
                'token': token,
                'lang': 'zh_CN',
                'f': 'json',
                'ajax': '1',
                'random': random.random(),
                'action': 'list_ex',
                'begin': '{}'.format(str(begin)),
                'count': '5',
                'query': '',
                'fakeid': fakeid,
                'type': '9'
            }
            print('翻页###################', begin)
            query_fakeid_response = requests.get(appmsg_url, cookies=cookies, headers=header, params=query_id_data)
            fakeid_list = query_fakeid_response.json().get('app_msg_list')
            for item in fakeid_list:
                print(item.get('link'))
            num -= 1
            begin = int(begin)
            begin += 5
            time.sleep(5)


def threadGetCount():
    global label1
    while (True):
        label1['text'] = '间隔时间:' + str(getPrice())
        label2['text'] = '文章数量:' + str(getZhuanfa())
        label3['text'] = '成功数量:' + str(getLiuyan())
        time.sleep(1)

def getPrice():
    global zan_count
    return zan_count

def getZhuanfa():
    global zhuanfa_count
    return zhuanfa_count


def getLiuyan():
    global liuyan_count
    return liuyan_count
# driver.quit()
root = Tk()
label1 = Label(root, text='0')
label2 = Label(root, text='0')
label3 = Label(root, text='0')
if __name__ == '__main__':
    import datetime

    # global root
    # root.maxsize(600, 400)
    root.minsize(300, 240)
    end_date = datetime.datetime.strptime("2018-10-25", "%Y-%m-%d")
    datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
    begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d %H:%M:%S")
    print(end_date)
    print(datetimenowTime)
    print(begin_date)
    if begin_date < end_date:
        print('还能用')
        root.title(u"公共号文章爬取")
        label = Label(root, fg='green')
        label['text'] = u'试用版' #正式版
        label.pack()
        Button(root, text='启动', command=fun).pack()
        Button(root, text='爬取', command=fun1).pack()
        # label1.pack()
        label2.pack()
        label3.pack()

        frame = Frame(root)
        frame.pack()
        lab1 = Label(frame, text="时间间隔:")
        lab1.grid(row=0, column=0, sticky=W)
        ent1 = Entry(frame)
        ent1.grid(row=0, column=1, sticky=W)
        ent1.insert(10, zan_max)
        # lab2 = Label(frame, text="转发数限额:")
        # lab2.grid(row=1, column=0)
        # ent2 = Entry(frame)
        # ent2.insert(10, zhuanfa_max)
        # ent2.grid(row=1, column=1, sticky=W)
        # lab3 = Label(frame, text="留言数限额:")
        # lab3.grid(row=2, column=0)
        # ent3 = Entry(frame)
        # ent3.insert(10, liuyan_max)
        # ent3.grid(row=2, column=1, sticky=W)
        # lab4 = Label(frame, text="中文留言内容:")
        # lab4.grid(row=3, column=0)
        # ent4 = Entry(frame)
        # ent4.insert(10, cn_liuyan)
        # ent4.grid(row=3, column=1, sticky=W)
        # lab5 = Label(frame, text="英文留言内容:")
        # lab5.grid(row=4, column=0)
        # ent5 = Entry(frame)
        # ent5.insert(10, en_liuyan)
        # ent5.grid(row=4, column=1, sticky=W)
        lab6 = Label(frame, text="公众邮箱:")
        lab6.grid(row=2, column=0)
        ent6 = Entry(frame)
        ent6.insert(10, login_no)
        ent6.grid(row=2, column=1, sticky=W)
        lab7 = Label(frame, text="登录密码:")
        lab7.grid(row=3, column=0)
        ent7 = Entry(frame, show='*')
        ent7.insert(10, login_pw)
        ent7.grid(row=3, column=1, sticky=W)


        def Submit():
            global liuyan_max, zan_max, zhuanfa_max, cn_liuyan, en_liuyan, login_no, login_pw
            zan_max = ent1.get()
            # zhuanfa_max = ent2.get()
            # liuyan_max = ent3.get()
            # cn_liuyan = ent4.get()
            # en_liuyan = ent5.get()
            login_no = ent6.get()
            login_pw = ent7.get()


        button = Button(frame, text="保存", command=Submit)
        button.grid(row=7, column=1, sticky=E)

        center(root)
        t = threading.Thread(target=threadGetCount, args=(), name='thread-refresh')
        t.setDaemon(True)
        t.start()
        root.mainloop()
        # dopx()
    else:
        print('不能用')
        from tkinter import *

        root.title("提醒")
        label = Label(root)
        label['text'] = u'试用期已过，请联系 guocdfeifei@163.com 获取正式版'
        label.pack()
        center(root)
        root.mainloop()